#include "sd_card.h"
#include <stdio.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>

#include "esp_vfs.h"
#include "esp_vfs_fat.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/sdmmc_defs.h"
#include "sdmmc_cmd.h"

static const char *TAG = "sd_card";

/***********************************************************/
/*********************    SD卡  ↓   *********************/
sdmmc_card_t *sdmmc_card = NULL;

// 挂载SD卡
esp_err_t bsp_sdcard_mount(void)
{
    ESP_LOGI(TAG, "Mounting SD card");
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = false,  // 加载不成功是否需要格式化
        .max_files = 5,                   // 最大文件数
        .allocation_unit_size = 8 * 1024
    };

    sdmmc_host_t sdmmc_host = SDMMC_HOST_DEFAULT(); // SDMMC主机接口配置
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); // SDMMC插槽配置
    slot_config.width = 1;  // 设置为1线SD模式
    slot_config.clk = SD_CLK_IO; 
    slot_config.cmd = SD_CMD_IO;
    slot_config.d0 = SD_DAT0_IO;
    slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP; // 打开内部上拉电阻

    ESP_LOGI(TAG, "Mounting filesystem Starting");

    esp_err_t ret = esp_vfs_fat_sdmmc_mount(SD_MOUNT_POINT, &sdmmc_host, &slot_config, &mount_config, &sdmmc_card);

    //    sdmmc_card_print_info(stdout, card);
    return ret;
}

esp_err_t bsp_sdcard_unmount(void)
{
    esp_err_t ret= esp_vfs_fat_sdcard_unmount(SD_MOUNT_POINT, sdmmc_card);

    sdmmc_card = NULL;

    return ret;
}
static bool sd_not_owner=false;
esp_err_t try_sdcard_mount(void)
{
    /*判断SD卡是否挂载，如果没有挂载，则尝试挂载  */

    // 检查挂载点目录是否存在
    // struct stat st;
    // if (stat(SD_MOUNT_POINT, &st) == 0 && S_ISDIR(st.st_mode)) {
    //     // 目录存在，尝试打开它确认是否可访问
    //     DIR *dir = opendir(SD_MOUNT_POINT);
    //     if (dir != NULL) {
    //         closedir(dir);
    //         ESP_LOGW(TAG, "Mount point exists but SD card not initialized properly");
    //         return ESP_OK;
    //     }
    // }
    if (sdmmc_card==NULL)
    {
        sd_not_owner=true;
        return bsp_sdcard_mount();
    }
    return ESP_OK;
}
esp_err_t try_sdcard_unmount(void)
{
    /*判断SD卡是否挂载，如果没有挂载，则尝试挂载  */
    if (sd_not_owner)
    {
        sd_not_owner = false;
        return bsp_sdcard_unmount();
    }
    return ESP_OK;
}
